package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.cache.service.IQuestionStatisVOService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.comment.domain.Answer;
import cn.wolfcode.luowowo.comment.domain.AnswerComment;
import cn.wolfcode.luowowo.comment.query.AnswerQuery;
import cn.wolfcode.luowowo.comment.service.IAnswerCommentService;
import cn.wolfcode.luowowo.comment.service.IAnswerService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.qanda.domain.Question;
import cn.wolfcode.luowowo.qanda.service.IQuestionService;
import cn.wolfcode.luowowo.qanda.service.IQuestionTagService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("question")
public class QuestionController {

    @Reference
    private IQuestionService questionService;

    @Reference
    private IStrategyStatisVOService strategyStatisVOService;

    @Reference
    private IQuestionTagService questionTagService;


    @Reference
    private IAnswerService answerService;

    @Reference
    private IAnswerCommentService answerCommentService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IQuestionStatisVOService questionStatisVOService;

    @RequestMapping("")
    public String question(Model model){
        //查询出所有的问题
        List<Question> questiones=questionService.query();
        //回复内容
        List<Question> questions=new ArrayList<>();
        for (Question question : questiones) {
            List<Answer> answers = answerService.findByQuestionId(question.getId());
            if(answers.size()!=0){
               Answer answer = answers.get(answers.size() - 1);
               question.setAnswer(answer);
               question.setDest(destinationService.findDestById(answer.getDestId()));
               question.setTag(questionTagService.findTagById(answer.getTagId()));
               questions.add(question);
            }else{
               questions.add(question);
            }

        }
        model.addAttribute("viewTop",answerService.findViewtop());
        model.addAttribute("thumbupTop",answerService.findthumbuptop());
        model.addAttribute("shareTop",answerService.findShareTop());
        model.addAttribute("questions",questions);
        return "/qanda/wenda";
    }

    @RequestMapping("createQuestion")
    public String createQuestion(Model model){
        model.addAttribute("dests",destinationService.list());
        //tag
        model.addAttribute("tags",questionTagService.query());
        return "qanda/publish";
    }

    @RequestMapping("addQuestion")
    @ResponseBody
    public Object addQuestion(Question question, @UserParam UserInfo userInfo){
        //判断用户有没有登录
        if(userInfo==null){
            throw new LogicException("你还没有登录噢!");
        }
        try{
            questionService.insert(question,userInfo);
            return new AjaxResult(true,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"添加失败");
        }
    }

    @RequestMapping("input")
    public String input(Long id,Model model){
        Question question = questionService.selectQuestionById(id);
        model.addAttribute("question",question);
        model.addAttribute("dests",destinationService.list());
        model.addAttribute("tags",questionTagService.query());
        return "/qanda/input";
    }

    @RequestMapping("addAnswer")
    @ResponseBody
    public Object addAnswer(Answer answer,@UserParam UserInfo userInfo){
        if(userInfo==null){
            throw new LogicException("你还没有登录哟");
        }
        answer.setUserId(userInfo.getId());
        answer.setUsername(userInfo.getNickname());
        answer.setUserLavel(userInfo.getLevel());
        answer.setHeadUrl(userInfo.getHeadImgUrl());
        answerService.save(answer);
        return AjaxResult.success().addData(answer.getQuestionId());
    }

    @Value("${file.path}")
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    @RequestMapping("selectQuestionById")
    public String selectQuestionById(Long id,Model model){
        AnswerQuery qo=new AnswerQuery();
        qo.setQuestionId(id);
        Question question=questionService.selectQuestionById(id);
        model.addAttribute("question",question);
       /* List<Answer> answers = answerService.findByQuestionId(id);
        model.addAttribute("answers",answers);*/
        Page page=answerService.query(qo);
        model.addAttribute("page",page);
        return "/qanda/wendaDetail";
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(AnswerComment comment, @UserParam UserInfo userInfo,Model model) {
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setLevel(userInfo.getLevel());
        comment=answerCommentService.save(comment);
        // 热门推荐加分
        //strategyStatisVOService.addHotScore(comment.getDetailId(), 1);

        //评论数 +1
        //strategyStatisVOService.increaseReplynum(comment.getDetailId(), 1);
        //.addData(strategyStatisVOService.getStrategyStatisVO(comment.getDetailId()).getReplynum())
        model.addAttribute("reply", comment);
        return "/qanda/replyTpl";
    }

    @RequestMapping("/answerThumbup")
    @ResponseBody
    public Object travelThumbup(@UserParam UserInfo userInfo, String sid) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "请先登录!");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        boolean ret = questionStatisVOService.QuestionThumbup(userInfo.getId(), sid);
        return new AjaxResult(ret, "").addData(questionStatisVOService.getQuestionStatisVO(sid,userInfo));
    }

}
